package xpn.platform.modules.sys.org;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.Length;
import org.springframework.data.rest.core.annotation.RestResource;
import xpn.platform.common.persistence.AbstractBaseEntity;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Entity
@Getter
@Setter
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" }, ignoreUnknown = true)
public class SysOrg extends AbstractBaseEntity {
	private static final long serialVersionUID = -6039695828223759207L;

	@Column(length = 60, nullable = false)
	@Length(min = 2, max = 60)
	@Getter
	@Setter
	private String orgName; // 机构名称

	private Integer type; // 机构类型

	private Boolean isOuter;//是否为外部单位 true:是

	private Integer businessType; // 业务类型  1:施工单位  2:监理单位  3:设计单位 4:供货单位

	@Column(length = 60)
	@Length(min = 1, max = 60)
	private String orgCode; // 机构编码

	@JoinColumn
	@ManyToOne(fetch = FetchType.LAZY)
	private SysOrg parentOrg; // 父亲机构

	private Float sortNo;

	// 包含的儿子机构
	@OneToMany(mappedBy = "parentOrg", fetch = FetchType.LAZY)
	@JsonIgnore
	@RestResource(exported = false)
	private Set<SysOrg> children = new HashSet<>();

	// 获取关联属性
	// 返回祖先的id
	@JsonIgnore
	public Long fetchAncestorId() {
		SysOrg parent = this.getParentOrg();
		if (parent == null) {
			return this.getId();
		}
		while (parent.getParentOrg() != null) {
			parent = parent.getParentOrg();
		}
		return parent.getId();
	}

	// 获取机构全名
	@JsonIgnore
	public String fetchFullName() {
		List<SysOrg> orgs=new ArrayList<SysOrg>();
		String orgFullName = "";
		for (SysOrg org = this; org != null;) {
			orgs.add(org);
			org=org.getParentOrg();
		}
		for(int i=orgs.size()-1;i>=0;i--){
			orgFullName += (orgFullName == "" ? "" : "/") + orgs.get(i).getOrgName();
		}
		return orgFullName;
	}

	// 获取机构全名
	@JsonIgnore
	public String fetchFullOrgCode() {
		String orgFullCode= "";
		for (SysOrg org = this; org != null;) {
			orgFullCode += (orgFullCode == "" ? "" : "/") + org.getOrgCode();
			org = org.getParentOrg();
		}
		return orgFullCode;
	}

}
